package JDBC;

import java.sql.*;

/**
 * @Fou Jack of all trades and master of none.
 * @date 2022/1/5 20:52
 */
public class DAOIncrement {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        PreparedStatement prestmt = null;
        ResultSet rs = null;
        try {
            //注册驱动
            DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
            //通过注册的驱动获取连接对象Connection
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/daodemodb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC","root","root");
            //通过PreparedStatement对象执行操作，返回结果ResultSet
            String sql = "insert into t_user (name,age,money) value(?,?,?)";
            prestmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            prestmt.setString(1,"绝地玩家");
            prestmt.setInt(2,25);
            prestmt.setDouble(3,989);
            //返回结果
            int result = prestmt.executeUpdate();
            if (result>0){
                System.out.println("新增成功！");
                rs=prestmt.getGeneratedKeys();
                while (rs.next()){
                    System.out.println("生成新的主键ID为："+rs.getInt(1));
                }
            }

        }catch (SQLException e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        finally {
            //释放资源
            if (conn!=null){
                conn.close();
            }
            if (prestmt!=null){
                prestmt.close();
            }
            if (rs!=null){
                rs.close();
            }
        }
    }

}
